package cn.kongwg.servlet;

import cn.kongwg.bean.Book;
import cn.kongwg.bean.Page;
import cn.kongwg.service.BookService;
import cn.kongwg.service.impl.BookServiceImpl;
import cn.kongwg.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author kongwg
 * @create 2021-01-27 13:27
 */
@WebServlet("/client/bookServlet")
public class ClientBookServlet extends BaseServlet {
    private BookService bookService = new BookServiceImpl();

    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNo = WebUtils.parseToInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseToInt(req.getParameter("pageSize"), Page.PAGE_SIZE);

        Page<Book> page = bookService.page(pageNo, pageSize);
        page.setUrl("client/bookServlet?action=page");
        req.setAttribute("page", page);

        req.getRequestDispatcher("/pages/client/index.jsp").forward(req, resp);

    }

    protected void pageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int pageNo = WebUtils.parseToInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseToInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        int min = WebUtils.parseToInt(req.getParameter("min"), 0);
        int max = WebUtils.parseToInt(req.getParameter("max"), Integer.MAX_VALUE);


        StringBuilder strPath = new StringBuilder("client/bookServlet?action=pageByPrice");
        Page<Book> list = bookService.pageByPrice(pageNo, pageSize, min, max);

        if (req.getParameter("min") != null) {
            strPath.append("&min=").append(req.getParameter("min"));
        }
        if (req.getParameter("max") != null) {
            strPath.append("&max=").append(req.getParameter("max"));
        }
        list.setUrl(strPath.toString());
        req.setAttribute("page", list);
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req, resp);
    }

}
